package com.heima.media.lisener;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Configuration
public class ReceiveLisener {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IWmNewsService wmNewsService;
    @Autowired
    IAuditService auditService;
    @PostConstruct
    public void Receiver(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    RBlockingDeque<Object> test_msg = redissonClient.getBlockingDeque("test_msg");
                    RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(test_msg);
                    delayedQueue.offer("init",1,TimeUnit.SECONDS);
                    while (true) {
                        Object poll = test_msg.poll(1, TimeUnit.MINUTES);
                        if (!StringUtils.isEmpty(poll)&&!poll.equals("init")){
                            WmNews wmNews = JSON.parseObject((String) poll, WmNews.class);
                            auditService.audit(wmNews);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
